<template>
  <view class="container">
    <!-- Transparent navigation bar -->
    <view class="nav-bar">
      <view class="navigation-buttons">
        <view class="nav-button" @click="goBack">
          <image src="/static/arrow-left.png" mode="aspectFit" class="nav-icon"></image>
        </view>
        <view class="nav-button" @click="goHome">
          <image src="/static/home-icon.png" mode="aspectFit" class="nav-icon"></image>
        </view>
      </view>
      <text class="page-title"> </text>
      <view class="placeholder"></view>
    </view>

    <!-- Product image carousel -->
    <swiper class="product-images" indicator-dots circular>
      <swiper-item v-if="pict_url">
        <image :src="pict_url" mode="aspectFill" style="width: 100%;height: 100%;"></image>
      </swiper-item>
      <swiper-item v-if="white_image">
        <image :src="white_image" mode="aspectFill" style="width: 100%;height: 100%;"></image>
      </swiper-item>
      <swiper-item v-for="(image, index) in small_images" :key="index">
        <image :src="image" mode="aspectFill" style="width: 100%;height: 100%;"></image>
      </swiper-item>
    </swiper>

    <!-- Product info card -->
    <view class="product-info-card">
      <!-- Price section -->
      <view class="price-section">
        <text class="current-price">¥{{ zk_final_price }}</text>
        <text class="original-price">¥{{ reserve_price }}</text>
      </view>

      <!-- Product title -->
      <view class="product-title">
        <text>{{ title }}</text>
      </view>

      <!-- Short title -->
      <view class="short-title">
        <text>{{ short_title }}</text>
      </view>

      <!-- Product info -->
      <view class="product-info-section">
        <view class="info-item">
          <text class="info-label">品牌：</text>
          <text class="info-value">{{ brand_name }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">类目：</text>
          <text class="info-value">{{ category_name }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">年销量：</text>
          <text class="info-value">{{ annual_vol }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">店铺：</text>
          <text class="info-value">{{ shop_title }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">发货地：</text>
          <text class="info-value">{{ provcity }}</text>
        </view>
      </view>

      <!-- Description heading -->
      <view class="description-heading">
        <text>商品描述</text>
      </view>

      <!-- Product description -->
      <view class="product-description">
        <text>{{ description || short_title }}</text>
      </view>

      <!-- 商品描述图片 -->
      <view class="product-description-images" v-if="small_images && small_images.length > 0">
        <view class="section-title">
          <text>商品详情图</text>
        </view>
        <view class="description-image-item" v-for="(image, index) in small_images" :key="'desc-'+index">
          <image :src="image" mode="widthFix" @click="previewImage(small_images, image)" @error="onImageError" @load="onImageLoad"></image>
        </view>
      </view>

      <!-- Add bottom padding to prevent content from being covered by action bar -->
      <view class="bottom-padding"></view>
    </view>

    <!-- Bottom action bar -->
    <view class="bottom-action-bar">
      <view class="action-buttons">
        <view class="action-button" @click="like">
          <image :src="isLiked ? '/static/heart-active.png' : '/static/heart-icon.png'" mode="aspectFit" class="action-icon"></image>
          <text class="label" :class="{ 'active': isLiked }">{{ isLiked ? '已点赞' : '点赞' }}</text>
        </view>
        <view class="action-button" @click="favorite">
          <image :src="isCollected ? '/static/favorite-active.png' : '/static/favorite.png'" mode="aspectFit" class="action-icon"></image>
          <text class="label" :class="{ 'active': isCollected }">{{ isCollected ? '已收藏' : '收藏' }}</text>
        </view>
        <view class="action-button" @click="share">
          <image src="/static/share.svg" mode="aspectFit" class="action-icon"></image>
          <text class="label">转发</text>
        </view>
      </view>
      <view class="main-action-button" @click="goToTaobao">
        <text class="taobao-icon">淘</text>
        <text>直达链接</text>
      </view>
    </view>
  </view>
</template>

<script>
import { getProductDetail } from '../../api/products.js';
import { addCollect, removeCollect } from '../../api/collect.js';
import { addLike, removeLike } from '../../api/like.js';

export default {
  data() {
    return {
      title: '',
      short_title: '',
      pict_url: '',
      white_image: '',
      small_images: [],
      zk_final_price: 0,
      reserve_price: 0,
      brand_name: '',
      category_name: '',
      level_one_category_name: '',
      annual_vol: '',
      shop_title: '',
      provcity: '',
      taocode: '',
      description: '',
      loading: false,
      error: null,
      isCollected: false,
      isLiked: false,
      productId: null
    }
  },
  onLoad(options) {
    if (options.id) {
      this.productId = options.id;
      this.fetchProductDetail(options.id);
    }
  },
  methods: {
    async fetchProductDetail(productId) {
      this.loading = true;
      this.error = null;
      try {
        const response = await getProductDetail({ productId });
        const {
          title, short_title, pict_url, white_image, small_images,
          zk_final_price, reserve_price, brand_name, category_name,
          level_one_category_name, annual_vol, shop_title, provcity,
          taocode, description, isCollect, isLike
        } = response.data;
        this.title = title;
        this.short_title = short_title;
        this.pict_url = pict_url;
        this.white_image = white_image;
        // Handle small_images structure from API
        this.small_images = Array.isArray(small_images) ? small_images : [];
        this.zk_final_price = zk_final_price;
        this.reserve_price = reserve_price;
        this.brand_name = brand_name;
        this.category_name = category_name;
        this.level_one_category_name = level_one_category_name;
        this.annual_vol = annual_vol;
        this.shop_title = shop_title;
        this.provcity = provcity;
        this.taocode = taocode;
        this.description = description;
        
        // 设置收藏和点赞状态
        this.isCollected = isCollect === 1;
        this.isLiked = isLike === 1;
      } catch (error) {
        this.error = '获取商品详情失败';
        uni.showToast({
          title: '获取商品详情失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    goBack() {
      uni.navigateBack();
    },
    goHome() {
      // Navigate to the home page
      uni.switchTab({
        url: '/pages/index/index'
      });
    },
    updateTime() {
      const now = new Date()
      const hours = now.getHours().toString().padStart(2, '0')
      const minutes = now.getMinutes().toString().padStart(2, '0')
      this.currentTime = `${hours}:${minutes}`
    },
    // Add methods for button actions
    async like() {
      if (!this.productId) return;
      
      try {
        if (this.isLiked) {
          await removeLike(this.productId);
          this.isLiked = false;
          uni.showToast({
            title: '已取消点赞',
            icon: 'none'
          });
        } else {
          await addLike(this.productId);
          this.isLiked = true;
          uni.showToast({
            title: '点赞成功',
            icon: 'none'
          });
        }
      } catch (error) {
        uni.showToast({
          title: this.isLiked ? '取消点赞失败' : '点赞失败',
          icon: 'none'
        });
      }
    },
    async favorite() {
      try {
        if (this.isCollected) {
          await removeCollect(this.productId);
          this.isCollected = false;
          uni.showToast({
            title: '已取消收藏',
            icon: 'none'
          });
        } else {
          await addCollect(this.productId);
          this.isCollected = true;
          uni.showToast({
            title: '收藏成功',
            icon: 'success'
          });
        }
      } catch (error) {
        uni.showToast({
          title: '操作失败',
          icon: 'error'
        });
      }
    },
    // 分享给好友
    onShareAppMessage(res) {
      const shareContent = {
        title: this.title || '商品详情',
        path: `/pages/product/detail?id=${this.productId}`, // 分享后打开的页面路径
        imageUrl: this.pict_url || this.small_images[0] || '/static/default-image.png', // 分享图片
      };
      console.log('Sharing to friends:', shareContent);
      return shareContent;
    },
    // 分享到朋友圈
    onShareTimeline() {
      const shareContent = {
        title: `${this.short_title || this.title} ¥${this.zk_final_price}`, // 朋友圈只支持标题
        query: `id=${this.productId}`, // 携带参数
        imageUrl: this.pict_url || this.small_images[0] || '/static/default-image.png', // 分享图片
      };
      console.log('Sharing to timeline:', shareContent);
      return shareContent;
    },
    async share() {
      // 点击转发按钮时可直接提示用户使用右上角分享
      uni.showToast({
        title: '请点击右上角"..."分享',
        icon: 'none',
        duration: 2000
      });
    },
    copyShareLink() {
      const shareText = `${this.title}\n${this.short_title}\n¥${this.zk_final_price}\n${this.taocode || '暂无链接'}`;
      uni.setClipboardData({
        data: shareText,
        success: () => {
          uni.showToast({
            title: '链接已复制',
            icon: 'success'
          });
        }
      });

    },
    goToTaobao() {
      // 示例淘宝口令，实际使用时应该从后端获取
      const tbCommand = this.taocode || '￥TAOBAO-CODE￥'
      uni.setClipboardData({
        data: tbCommand,
        success: () => {
          uni.showModal({
            title: '淘宝口令已复制',
            content: '请打开淘宝APP查看商品详情',
            showCancel: false,
            confirmText: '我知道了'
          })
        }
      })
    },
    previewImage(urls, current) {
      // 如果只传了一个参数，说明是旧的调用方式
      if (arguments.length === 1) {
        current = urls;
        urls = Array.isArray(this.small_images) ? this.small_images : [];
      }
      
      if (!Array.isArray(urls) || urls.length === 0) {
        uni.showToast({
          title: '暂无图片',
          icon: 'none'
        });
        return;
      }
      
      uni.previewImage({
        urls,
        current
      });
    },
    onImageError(e) {
      console.log('图片加载失败:', e);
      uni.showToast({
        title: '图片加载失败',
        icon: 'none'
      });
    },
    onImageLoad(e) {
      console.log('图片加载成功:', e);
    }
  }
}
</script>

<style>
.container {
  flex: 1;
  position: relative;
  background-color: #f5f5f5;
}

.status-bar {
  height: 88rpx;
  background-color: #ffffff;
  color: #333333;
  padding: 44rpx 32rpx 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.time {
  font-size: 28rpx;
}

.right-icons {
  display: flex;
  gap: 16rpx;
  font-size: 24rpx;
}

.product-images {
  height: 750rpx;
  width: 100%;
  background-color: #f5f5f5;
}

.nav-bar {
  position: fixed;
  top: 34rpx;
  left: 0;
  right: 0;
  height: 120rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 44rpx 32rpx 0;
  z-index: 100;
}

.navigation-buttons {
  display: flex;
  gap: 24rpx;
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 40rpx;
  padding: 10rpx 20rpx;
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
}

.nav-button {
  width: 64rpx;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s ease;
}

.nav-button:active {
  transform: scale(0.92);
  background-color: rgba(255, 255, 255, 0.1);
}

.nav-icon {
  width: 40rpx;
  height: 40rpx;
  filter: drop-shadow(0 2rpx 4rpx rgba(0, 0, 0, 0.2));
}

.page-title {
  color: #ffffff;
  font-size: 34rpx;
  font-weight: 600;
  letter-spacing: 2rpx;
  text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.4);
}

.placeholder {
  width: 72rpx;
}

.product-info-card {
  background-color: #ffffff;
  border-radius: 24rpx 24rpx 0 0;
  padding: 32rpx;
  margin: -90rpx 24rpx 0;
  position: relative;
  z-index: 1;
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.05);
}

.price-section {
  display: flex;
  align-items: baseline;
  gap: 16rpx;
  margin-bottom: 24rpx;
}

.current-price {
  font-size: 56rpx;
  font-weight: bold;
  color: #881B20;
  text-shadow: 0 2rpx 4rpx rgba(136, 27, 32, 0.1);
}

.original-price {
  font-size: 32rpx;
  color: #999999;
  text-decoration: line-through;
}

.product-title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  line-height: 1.4;
  color: #333333;
  text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.05);
}

.price-source {
  font-size: 26rpx;
  color: #666666;
  margin-bottom: 36rpx;
  background-color: #f8f8f8;
  padding: 12rpx 20rpx;
  border-radius: 8rpx;
  display: inline-block;
}

.description-heading {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  color: #333333;
  position: relative;
  padding-left: 24rpx;
}

.description-heading::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 8rpx;
  height: 32rpx;
  background-color: #881B20;
  border-radius: 4rpx;
}

.product-description {
  font-size: 30rpx;
  color: #666666;
  line-height: 1.6;
  margin-bottom: 36rpx;
  background-color: #f8f8f8;
  padding: 24rpx;
  border-radius: 16rpx;
  text-align: justify;
}

.short-title {
  font-size: 28rpx;
  color: #666666;
  margin-bottom: 24rpx;
  line-height: 1.4;
}

.product-info-section {
  background-color: #f8f8f8;
  padding: 24rpx;
  border-radius: 16rpx;
  margin-bottom: 36rpx;
}

.info-item {
  display: flex;
  margin-bottom: 16rpx;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-label {
  font-size: 28rpx;
  color: #666666;
  width: 140rpx;
}

.info-value {
  font-size: 28rpx;
  color: #333333;
  flex: 1;
}

.decorative-line {
  height: 24px;
  margin: 16px 0;
}

.bottom-image-placeholder {
  height: 150px;
  background-color: #f5f5f5;
  margin: 0 -16px;
}

.bottom-action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 120rpx;
  background-color: #fff;
  border-top: 1rpx solid #eee;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx;
  z-index: 100;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.action-buttons {
  display: flex;
  gap: 48rpx;
}

.action-button {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
}

.action-button .icon {
  font-size: 48rpx;
  color: #666;
}

.action-button .label {
  font-size: 24rpx;
  color: #666;
}

.label.active {
  color: #c73535;
}

.main-action-button {
  background-color: #c73535;
  color: #fff;
  height: 88rpx;
  border-radius: 44rpx;
  padding: 0 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  font-weight: bold;
  box-shadow: 0 4rpx 12rpx rgba(199, 53, 53, 0.3);
  transition: all 0.3s ease;
}

.main-action-button:active {
  transform: scale(0.98);
  box-shadow: 0 2rpx 8rpx rgba(199, 53, 53, 0.2);
}

.bottom-padding {
  height: 140rpx;
}

.product-description-images {
  padding: 24rpx;
  background-color: #f8f8f8;
  border-radius: 16rpx;
  margin-bottom: 36rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  color: #333333;
  position: relative;
  padding-left: 24rpx;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 8rpx;
  height: 32rpx;
  background-color: #881B20;
  border-radius: 4rpx;
}

.description-image-item {
  margin-bottom: 16rpx;
}

.description-image-item:last-child {
  margin-bottom: 0;
}

.description-image-item image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8rpx;
}

.action-icon {
  width: 48rpx;
  height: 48rpx;
}
</style>